package com.cyj.dream.auth.persistence.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyj.dream.auth.entity.SysRole;
import com.cyj.dream.auth.entity.SysUser;
import com.cyj.dream.auth.entity.SysUserRole;
import com.cyj.dream.auth.persistence.service.ITbSysRoleService;
import com.cyj.dream.auth.persistence.service.ITbSysUserRoleService;
import com.cyj.dream.auth.persistence.service.ITbSysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 用户服务实现层
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.auth.persistence.service.impl
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-30 10:38
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Service
public class CustomUserServiceImpl implements UserDetailsService {

    @Autowired
    private ITbSysUserService iTbSysUserService;

    @Autowired
    private ITbSysRoleService iTbSysRoleService;

    @Autowired
    private ITbSysUserRoleService iTbSysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("接受到的userName为：{}", userName);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, userName);
        //获取本地用户
        SysUser sysUser = iTbSysUserService.getOne(wrapper);

        String str = "是";

        if (ObjectUtil.isEmpty(sysUser)) {
            throw new UsernameNotFoundException("用户[" + userName + "]不存在，Login account does not exist!!!");
        }

        // 是否允许登录
        if (str.equals(sysUser.getSysUserIsLock())) {
            throw new UsernameNotFoundException("当前用户已锁定禁止登陆，如需登录请联系管理员~");
        }

        //有扩展手机号验证码登录，所以校验一下是否设置密码
        if (StrUtil.isEmpty(sysUser.getPassword())) {
            throw new UsernameNotFoundException("未设置登录密码");
        }

        LambdaQueryWrapper<SysUserRole> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysUserRole::getSysUserId, sysUser.getDreamId());
        List<SysUserRole> sysUserRoleList = iTbSysUserRoleService.list(wrapper1);
        if(CollUtil.isNotEmpty(sysUserRoleList)){
            // 从对象列表中提取一列
            List<Long> userIdList = sysUserRoleList.stream().map(SysUserRole::getSysUserId).collect(Collectors.toList());
            LambdaQueryWrapper<SysRole> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.in(SysRole::getDreamId, userIdList);
            List<SysRole> sysRoleList = iTbSysRoleService.list(wrapper2);
            if(CollUtil.isNotEmpty(sysRoleList)){
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                List<String> roleList = sysRoleList.stream().map(SysRole::getSysRoleTrueName).collect(Collectors.toList());
                authorities.add(new SimpleGrantedAuthority(JSONObject.toJSONString(roleList)));
            }
        }

        //返回oauth2的用户
        return sysUser;
            /*return new org.springframework.security.core.userdetails.User(
                    sysUser.getUsername(),
                    sysUser.getPassword(),
                    AuthorityUtils.createAuthorityList(sysUser.getRolesSet())) ;*/
    }


}
